<template>
  <div class="play-type" ref="tabBar">
    <span
      ref="tabs"
      v-for="(game, index) in data"
      :class="currentPlayTypeIndex === index ? 'active-play' : ''"
      @click="selectPlayType(index)"
      :key="index"
    >
      {{ game.playTypeName }}
    </span>
  </div>
</template>

<script>
export default {
  props: {
    data: {
      type: Array,
      default: () => {
        return []
      },
    },
  },
  data() {
    return {
      currentPlayTypeIndex: 0, //当前的索引
    }
  },
  watch: {
    data() {
      this.selectPlayType(0)
    },
  },
  methods: {
    selectPlayType(index) {
      this.currentPlayTypeIndex = index
      this.$emit('selectPlayType', index)
      // 获取标签栏容器的 DOM 元素
      const tabBarElement = this.$refs.tabBar
      // 获取要滚动的标签元素
      const targetTabElement = this.$refs.tabs[index]
      // clientWidth
      // 计算所有标签的总宽度
      const totalTabsWidth = Array.from(tabBarElement.children).reduce((width, tab) => width + tab.clientWidth, 0)
      // 计算滚动的距离，使目标标签滚动到容器的中央
      const scrollOffset = targetTabElement.offsetLeft - (tabBarElement.clientWidth - targetTabElement.clientWidth) / 2
      // 计算滚动的最大距离，以确保不超出标签栏的边界
      const maxScrollOffset = totalTabsWidth - tabBarElement.clientWidth + targetTabElement.clientWidth / 2
      // 使用 scrollLeft 属性滚动标签栏，并确保在边界内滚动
      tabBarElement.scrollLeft = Math.max(0, Math.min(maxScrollOffset, scrollOffset))
    },
  },
}
</script>

<style scoped lang="less">
.play-type {
  display: flex;
  justify-content: flex-start;
  white-space: nowrap;
  overflow-x: auto;
  padding-bottom: 10px;
  box-sizing: border-box;

  span {
    display: block;
    background: linear-gradient(180deg, #333950 0%, #24253d 100%);
    color: #7b85a6;
    border-radius: 10px;
    font-size: 12px;
    padding: 0 10px;
    margin-right: 5px;
    line-height: 24px;
    text-align: center;
    box-sizing: border-box;
  }

  .active-play {
    background: linear-gradient(182.69deg, #9a9eff -11.69%, #644bff 74.43%, #9281ff 107.71%);
    color: #ffffff;
  }
}
</style>
